var createError = require('http-errors');
var express = require('express');
var path = require('path');
var logger = require('morgan');

//session/cookie
var cookieParser = require('cookie-parser');
var session=require("express-session");

//解决跨域
var cors=require("cors");

//前提
var mongoose = require('mongoose');


//mongodb4.x连接数据库时，要带上{ useNewUrlParser: true }
mongoose.connect('mongodb://localhost:27017/managers', {useNewUrlParser: true})

var loginRouter = require('./routes/login');
var usersRouter = require('./routes/users');
var cateRouter = require('./routes/cate');
var catetypeRouter = require('./routes/catetype');
var newsRouter = require('./routes/news');
var productRouter = require('./routes/product');
var commentRouter = require('./routes/comment');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'public')));

app.use(cors());
app.use(cookieParser());//cookie 设置中间件

//设置session
app.use(session({
  name: 'session-name', // 这里是cookie的name，默认是connect.sid
  secret: 'recommend 128 bytes random string', // 建议使用 128 个字符的随机字符串
  resave: true,// 是否自动保存未初始化的会话，建议false
  saveUninitialized: true,// 是否每次都重新保存会话，建议false
  cookie: { maxAge: 24 * 60 * 1000, httpOnly: true }
}));


//解决跨域携带cookie
app.use(function(req, res, next){
  //设置可访问的域名 req.headers.orgin为nodejs下获取访问的域名地址
  res.header("Access-Control-Allow-Origin", req.headers.origin);
  //设置可访问方法名
  res.header('Access-Control-Allow-Methods', req.headers['Access-Control-Allow-Methods']);
  //设置可访问的头
  res.header('Access-Control-Allow-Headers', req.headers['access-control-request-headers']);
  //设置cookie时长
  res.header("Access-Control-Max-Age","1728000");
  //允许凭证,解决session跨域丢失问题
  res.header('Access-Control-Allow-Credentials', 'true');
  next();
});

app.use('/login', loginRouter);
app.use('/users', usersRouter);
app.use('/cate', cateRouter);
app.use('/catetype', catetypeRouter);
app.use('/news', newsRouter);
app.use('/product', productRouter);
app.use('/comment', commentRouter);







// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
